package com.oceansoft.mobile.econsole.weixin.api;

import com.oceansoft.mobile.econsole.modules.api.entity.DriveInfoIllegal;
import com.oceansoft.mobile.econsole.modules.api.entity.TransferredInform;
import com.oceansoft.mobile.econsole.modules.api.entity.ViolationInfo;
import com.oceansoft.mobile.econsole.modules.api.entity.YearlyCheckDue;
import com.oceansoft.mobile.econsole.weixin.api.config.ApiConfig;
import com.oceansoft.mobile.econsole.weixin.api.enums.ResultType;
import com.oceansoft.mobile.econsole.weixin.api.response.BaseResponse;
import com.oceansoft.mobile.econsole.weixin.message.*;
import com.oceansoft.mobile.econsole.weixin.util.BeanUtil;
import com.oceansoft.mobile.econsole.weixin.util.JSONUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息相关API
 *
 * @author xujin
 * @since 1.2
 */
public class MessageAPI extends BaseAPI {

    private static final Logger LOG = LoggerFactory.getLogger(MessageAPI.class);

    public MessageAPI(ApiConfig config) {
        super(config);
    }
    
    /**
     * 模板ID 3mewoFdy1VYKF6FGxeFVDyV75tc8lUgN2hB_zRNDfqc
     * @param violist 违章模板消息
     * @return
     */
    public ResultType sendTemplateMessage(List<ViolationInfo> violist){
        BeanUtil.requireNonNull(violist, "violist is null");
        LOG.debug("===============发送违章消息===============");
        String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=#";
        
        for(ViolationInfo vio:violist){
            final Map<String, Object> params = new HashMap<String, Object>();
            params.put("template_id", "3mewoFdy1VYKF6FGxeFVDyV75tc8lUgN2hB_zRNDfqc");
            params.put("touser", vio.getOpenid());
            params.put("topcolor", "#FF0000");
        	
            Map<String, TemplateMsg> param = new HashMap<String, TemplateMsg>();
            param.put("first", new TemplateMsg("您好，您的车辆"+vio.getLicense()+"发生了一宗交通违法行为", "#173177"));			//标题
            param.put("behaviour", new TemplateMsg(vio.getViolation(), "#173177"));		//违法行为
            param.put("time", new TemplateMsg(vio.getTime(), "#173177"));			//违法时间
            param.put("address", new TemplateMsg(vio.getAddress(), "#173177"));		//违法地点
            param.put("pay", new TemplateMsg(vio.getFins()+"", "#173177"));			//罚款
            param.put("score", new TemplateMsg(vio.getWfjfs(), "#173177"));			//记分
            param.put("remark", new TemplateMsg("太仓交警提醒您：安全驾驶是每个司机的责任与义务！", "#173177"));		//备注
            params.put("data", param);
            
            LOG.debug("openid【"+vio.getOpenid()+"】");
            LOG.debug("违章车辆【"+vio.getLicense()+"】,违法行为【"+vio.getViolation()+"】,违法时间【"+vio.getTime()+"】");
            LOG.debug("违章地点【"+vio.getAddress()+"】,罚款【"+vio.getFins()+"】,记分【"+vio.getWfjfs()+"】");
            BaseResponse response = executePost(url, JSONUtil.toJson(params));
            LOG.debug("=======模板消息发送结果========" + response.getErrcode() + "====" + response.getErrmsg());
        }
        
        return null;
	}

    /**
     * 模板ID v_A56nJpeAcuzlNdLhrbYjUbLaqvZrIMWnvHuxhLzsc
     * @param drilist
     * @return
     */
    public ResultType sendDriveInfoIllegalTemplateMessage(List<DriveInfoIllegal> drilist){
        BeanUtil.requireNonNull(drilist, "drilist is null");
        LOG.debug("===============发送驾驶证违法通知===============");
        String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=#";

        for(DriveInfoIllegal dri:drilist){
            final Map<String, Object> params = new HashMap<String, Object>();
            params.put("template_id","v_A56nJpeAcuzlNdLhrbYjUbLaqvZrIMWnvHuxhLzsc");
            params.put("touser",dri.getOpenid());
            params.put("topcolor","#FF0000");

            Map<String, TemplateMsg> param = new HashMap<String, TemplateMsg>();
            param.put("first", new TemplateMsg("您好，您有一条新违法通知。","#173177"));
            param.put("credentialsType",new TemplateMsg("驾驶证号","#173177"));
            param.put("credentialsAccount",new TemplateMsg(dri.getDrivingLicense(),"#173177"));
            param.put("behaviour",new TemplateMsg(dri.getIllegalBehavior(),"#173177"));
            param.put("time",new TemplateMsg(dri.getIllegalTime(),"#173177"));
            param.put("address",new TemplateMsg(dri.getAddress(),"#173177"));
            param.put("remark",new TemplateMsg("如有异议，可以直接留言反馈。","#173177"));
            params.put("data",param);

            LOG.debug("openid【"+dri.getOpenid()+"】");
            LOG.debug("驾驶证号【"+dri.getDrivingLicense()+"】,违法行为【"+dri.getIllegalBehavior()+"】");
            LOG.debug("违法时间【"+dri.getIllegalTime()+"】,违法地点【"+dri.getAddress()+"】");
            BaseResponse response = executePost(url, JSONUtil.toJson(params));
            LOG.debug("=======模板消息发送结果========" + response.getErrcode() + "====" + response.getErrmsg());
        }

        return null;
    }

    /**
     * 模板ID c2JehCS5sF36q7ZgBEKL1aBF9ie0bAXz5oUuiqWnm9Y
     * @param tranlist
     * @return
     */
    public ResultType sendTransferredInformTemplateMessage(List<TransferredInform> tranlist){
        BeanUtil.requireNonNull(tranlist, "tranlist is null");
        LOG.debug("===============发送办件办结通知===============");
        String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=#";
        for(TransferredInform tran:tranlist){
            final Map<String, Object> params = new HashMap<String, Object>();
            params.put("template_id", "c2JehCS5sF36q7ZgBEKL1aBF9ie0bAXz5oUuiqWnm9Y");
            params.put("touser", tran.getOpenid());
            params.put("topcolor", "#FF0000");

            Map<String, TemplateMsg> param = new HashMap<String, TemplateMsg>();
            param.put("first",new TemplateMsg("你好，您上报的"+ tran.getTransactName() +"办件已处置完毕。","#173177"));
            param.put("keyword1",new TemplateMsg(tran.getStartDoTime(),"#173177"));
            param.put("keyword2",new TemplateMsg(tran.getStatus(),"#173177"));
            param.put("keyword3",new TemplateMsg(tran.getTransferredTime(),"#173177"));
            param.put("remark",new TemplateMsg("感谢你的参与和支持。","#173177"));
            params.put("data",param);

            LOG.debug("openid【"+tran.getOpenid()+"】");
            LOG.debug("办件名称【"+tran.getTransactName()+"】,上报时间【"+tran.getStartDoTime()+"】");
            LOG.debug("状态【"+tran.getStatus()+"】,办结时间【"+tran.getTransferredTime()+"】");
            BaseResponse response = executePost(url, JSONUtil.toJson(params));
            LOG.debug("=======模板消息发送结果========" + response.getErrcode() + "====" + response.getErrmsg());
        }

        return null;
    }

    /**
     * 模板ID SGovldnvd4J1wHwoZRwJp9Gw_1TKs4OvIECa-j96TGs
     * @param yealist 车辆年检到期模板消息
     * @return
     */
    public ResultType sendCarYearlyCheckDueTemplateMessage(List<YearlyCheckDue> yealist){
        BeanUtil.requireNonNull(yealist, "yealist is null");
        LOG.debug("===============发送年检到期提醒===============");
        String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=#";

        for(YearlyCheckDue yea:yealist){
            final Map<String, Object> params = new HashMap<String, Object>();
            params.put("template_id","SGovldnvd4J1wHwoZRwJp9Gw_1TKs4OvIECa-j96TGs");
            params.put("touser",yea.getOpenid());
            params.put("topcolor", "#FF0000");

            Map<String, TemplateMsg> param =  new HashMap<String, TemplateMsg>();
            param.put("first", new TemplateMsg("尊敬的用户您好，您绑定的车辆即将到达年检日期","#173177"));
            param.put("keyword1",new TemplateMsg(yea.getLicenseNumber(),"#173177")); //车辆号牌
            param.put("keyword2",new TemplateMsg(yea.getCheckDueTime(),"#173177")); //年检有效期止
            param.put("remark",new TemplateMsg("若年检时间有误，请到交管部门进行核实！","#173177"));
            params.put("data",param);

            LOG.debug("openid【"+yea.getOpenid()+"】");
            LOG.debug("车辆号牌【"+yea.getLicenseNumber()+"】,年检有效期止【"+yea.getCheckDueTime()+"】");
            BaseResponse response = executePost(url, JSONUtil.toJson(params));
            LOG.debug("=======模板消息发送结果========" + response.getErrcode() + "====" + response.getErrmsg());
        }
        return null;
    }




    /**
     * 发布客服消息
     *
     * @param openid  关注者ID
     * @param message 消息对象，支持各种消息类型
     * @return 调用结果
     */
    public ResultType sendCustomMessage(String openid, BaseMsg message) {
        BeanUtil.requireNonNull(openid, "openid is null");
        BeanUtil.requireNonNull(message, "message is null");
        LOG.debug("发布客服消息......");
        String url = BASE_API_URL + "cgi-bin/message/custom/send?access_token=#";
        final Map<String, Object> params = new HashMap<String, Object>();
        params.put("touser", openid);
        if (message instanceof TextMsg) {
            TextMsg msg = (TextMsg) message;
            params.put("msgtype", "text");
            Map<String, String> text = new HashMap<String, String>();
            text.put("content", msg.getContent());
            params.put("text", text);
        } else if (message instanceof ImageMsg) {
            ImageMsg msg = (ImageMsg) message;
            params.put("msgtype", "image");
            Map<String, String> image = new HashMap<String, String>();
            image.put("media_id", msg.getMediaId());
            params.put("image", image);
        } else if (message instanceof VoiceMsg) {
            VoiceMsg msg = (VoiceMsg) message;
            params.put("msgtype", "voice");
            Map<String, String> voice = new HashMap<String, String>();
            voice.put("media_id", msg.getMediaId());
            params.put("voice", voice);
        } else if (message instanceof VideoMsg) {
            VideoMsg msg = (VideoMsg) message;
            params.put("msgtype", "video");
            Map<String, String> video = new HashMap<String, String>();
            video.put("media_id", msg.getMediaId());
            video.put("thumb_media_id", msg.getMediaId());
            video.put("title", msg.getTitle());
            video.put("description", msg.getDescription());
            params.put("video", video);
        } else if (message instanceof MusicMsg) {
            MusicMsg msg = (MusicMsg) message;
            params.put("msgtype", "music");
            Map<String, String> music = new HashMap<String, String>();
            music.put("thumb_media_id", msg.getThumbMediaId());
            music.put("title", msg.getTitle());
            music.put("description", msg.getDescription());
            music.put("musicurl", msg.getMusicUrl());
            music.put("hqmusicurl", msg.getHqMusicUrl());
            params.put("music", music);
        } else if (message instanceof NewsMsg) {
            NewsMsg msg = (NewsMsg) message;
            params.put("msgtype", "news");
            Map<String, Object> news = new HashMap<String, Object>();
            List<Object> articles = new ArrayList<Object>();
            List<Article> list = msg.getArticles();
            for (Article article : list) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("title", article.getTitle());
                map.put("description", article.getDescription());
                map.put("url", article.getUrl());
                map.put("picurl", article.getPicUrl());
                articles.add(map);
            }
            news.put("articles", articles);
            params.put("news", news);
        }
        BaseResponse response = executePost(url, JSONUtil.toJson(params));
        return ResultType.get(response.getErrcode());
    }
}
